'use client';

// 资源导入页面 - 天翼云分享码导入
// REF: API-SHARE189-004@v1.0

import React, { useEffect, useState } from 'react';
import { RefreshCw, LogIn, AlertCircle } from 'lucide-react';
import { useRouter } from 'next/navigation';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/use-toast';
import { useConfirmDialog } from '@/components/ui/confirm-dialog';
import { useAuth } from '@/contexts/AuthContext';
import { FileSearch, PackageOpen, Search } from 'lucide-react';
import { LoginForm } from '@/components/auth/LoginForm';

// 导入模块化组件
import { ShareCodeList } from '@/components/import/ShareCodeList';
import { ShareDetailDialog } from '@/components/import/ShareDetailDialog';
import { ShareCodePreviewDialog } from '@/components/import/ShareCodePreviewDialog';
import { BatchImportDialog } from '@/components/import/BatchImportDialog';
import { FolderSelectDialog } from '@/components/import/FolderSelectDialog';
import { ImportApiService } from '@/components/import/api';
import type { ShareCode, PaginationInfo } from '@/components/import/types';

// 类型定义、工具函数和组件已从 @/components/import 模块导入

export default function ImportPage() {
  const { toast } = useToast();
  const { showConfirm, ConfirmDialog } = useConfirmDialog();
  const { isAuthenticated, user, loading: authLoading, initialCheckDone } = useAuth();
  const router = useRouter();

  const handleLoginSuccess = () => {
    toast({
      title: '登录成功',
      description: '现在可以使用导入功能了',
    });
  };
  
  // 状态管理
  const [shareList, setShareList] = useState<ShareCode[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState<PaginationInfo>({
    page: 1,
    perPage: 10,
    total: 0,
    pages: 0,
    hasNext: false,
    hasPrev: false
  });
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<number | ''>('');
  
  // 详情对话框状态
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [selectedShare, setSelectedShare] = useState<ShareCode | null>(null);
  const [previewDialogOpen, setPreviewDialogOpen] = useState(false);
  const [batchImportDialogOpen, setBatchImportDialogOpen] = useState(false);
  const [folderSelectDialogOpen, setFolderSelectDialogOpen] = useState(false);
  const [pendingImportShareId, setPendingImportShareId] = useState<number | null>(null);

  // 加载分享码列表
  const loadShareList = async (page = 1) => {
    setLoading(true);
    try {
      const statusFilterValue = statusFilter === '' ? undefined : statusFilter.toString();
      const data = await ImportApiService.getShareList(
        page,
        pagination.perPage,
        statusFilterValue
      );
      setShareList(data.items || []);
      setPagination(data.pagination || pagination);
    } catch (error) {
      toast({
        title: '网络错误',
        description: '请检查网络连接',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

  // 解析分享码
  const handleParseShareCode = async (shareId: number) => {
    try {
      await ImportApiService.parseShareCode(shareId);
      toast({
        title: '解析请求已提交',
        description: '分享码正在解析中，请稍后刷新查看结果'
      });
      loadShareList(pagination.page);
    } catch (error: any) {
      toast({
        title: '解析失败',
        description: error.message || '解析分享码失败',
        variant: 'destructive'
      });
    }
  };

  // 删除分享码
  const handleDeleteShareCode = async (shareId: number) => {
    const confirmed = await showConfirm({
      title: '确认删除',
      description: '确定要删除这个分享码吗？此操作无法撤销。',
      confirmText: '删除',
      cancelText: '取消'
    });

    if (confirmed) {
      try {
        await ImportApiService.deleteShareCode(shareId);
        toast({
          title: '删除成功',
          description: '分享码已删除'
        });
        loadShareList(pagination.page);
      } catch (error: any) {
        toast({
          title: '删除失败',
          description: error.message || '删除分享码失败',
          variant: 'destructive'
        });
      }
    }
  };

  // 导入到虚拟网盘
  const handleImportToVirtualDisk = async (shareId: number) => {
    if (!user?.id) {
      toast({
        title: '用户信息错误',
        description: '请重新登录后再试',
        variant: 'destructive'
      });
      return;
    }

    // 打开文件夹选择对话框
    setPendingImportShareId(shareId);
    setFolderSelectDialogOpen(true);
  };

  // 执行实际导入
  const handleConfirmImport = async (targetFolderId?: number) => {
    if (!user?.id || !pendingImportShareId) {
      return;
    }

    try {
      const result = await ImportApiService.importToVirtualDisk(
        pendingImportShareId, 
        user.id, 
        targetFolderId,
        'rename', // 冲突策略：自动重命名
        true      // 保持目录结构
      );
      toast({
        title: '导入成功',
        description: `已成功导入 ${result.totalFiles || 0} 个文件`
      });
      loadShareList(pagination.page);
      setFolderSelectDialogOpen(false);
      setPendingImportShareId(null);
    } catch (error: any) {
      toast({
        title: '导入失败',
        description: error.message || '导入到虚拟网盘失败',
        variant: 'destructive'
      });
    } finally {
      setFolderSelectDialogOpen(false);
      setPendingImportShareId(null);
    }
  };

  // 搜索功能
  const handleSearch = () => {
    loadShareList(1); // 搜索时重置到第一页
  };

  // 初始化加载
  useEffect(() => {
    if (isAuthenticated) {
      loadShareList();
    }
  }, [statusFilter, isAuthenticated]);

  // 等待认证检查完成
  if (!initialCheckDone || authLoading) {
    return (
      <div className="p-6 flex items-center justify-center min-h-[60vh]">
        <div className="text-center">
          <RefreshCw className="h-8 w-8 animate-spin mx-auto mb-4 text-gray-400" />
          <p className="text-gray-600">正在检查登录状态...</p>
        </div>
      </div>
    );
  }

  // 如果未登录，显示登录表单
  if (!isAuthenticated) {
    return (
      <div className="p-6 flex items-center justify-center min-h-[60vh]">
        <div className="w-full max-w-md space-y-4">
          <div className="text-center mb-6">
            <h1 className="text-2xl font-bold text-gray-900 mb-2">资源导入</h1>
            <p className="text-gray-600">请先登录以使用导入功能</p>
          </div>
          <LoginForm onLoginSuccess={handleLoginSuccess} />
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">资源导入</h1>
          <p className="text-gray-600 mt-1">天翼云分享码导入和管理</p>
        </div>
        <Button onClick={() => loadShareList()} disabled={loading}>
          <RefreshCw className={`h-4 w-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
          刷新
        </Button>
      </div>

      {/* 功能按钮 */}
      <div className="flex items-center gap-3">
        <Button
          onClick={() => setPreviewDialogOpen(true)}
          variant="outline"
          className="flex items-center gap-2"
        >
          <FileSearch className="h-4 w-4" />
          预览解析
        </Button>
        
        <Button
          onClick={() => setBatchImportDialogOpen(true)}
          className="flex items-center gap-2"
        >
          <PackageOpen className="h-4 w-4" />
          批量导入
        </Button>
      </div>
      
      {/* 分享码列表 */}
      <ShareCodeList
        shareList={shareList}
        loading={loading}
        pagination={pagination}
        searchQuery={searchQuery}
        statusFilter={statusFilter.toString()}
        onSearchChange={setSearchQuery}
        onStatusFilterChange={(status) => setStatusFilter(status === 'all' ? '' : parseInt(status))}
        onSearch={handleSearch}
        onPageChange={(page) => {
          setPagination(prev => ({ ...prev, page }));
          loadShareList(page);
        }}
        onViewDetail={async (shareId) => {
          try {
            const shareDetail = await ImportApiService.getShareDetail(shareId);
            setSelectedShare(shareDetail);
            setDetailDialogOpen(true);
          } catch (error: any) {
            toast({
              title: '获取详情失败',
              description: error.message || '获取分享码详情失败',
              variant: 'destructive'
            });
          }
        }}
        onParse={handleParseShareCode}
        onDelete={handleDeleteShareCode}
        onImportToVirtualDisk={handleImportToVirtualDisk}
        onRefresh={loadShareList}
      />

      {/* 预览解析对话框 */}
      <ShareCodePreviewDialog
        open={previewDialogOpen}
        onOpenChange={setPreviewDialogOpen}
        onAddToList={(shareCode) => {
          // 添加到列表后刷新
          loadShareList();
          setPreviewDialogOpen(false);
        }}
      />

      {/* 批量导入对话框 */}
      <BatchImportDialog
        open={batchImportDialogOpen}
        onOpenChange={setBatchImportDialogOpen}
        onRefresh={() => {
          // 导入完成后刷新列表
          loadShareList();
        }}
      />

      {/* 详情对话框 */}
      <ShareDetailDialog
        open={detailDialogOpen}
        onOpenChange={setDetailDialogOpen}
        shareData={selectedShare}
      />

      {/* 文件夹选择对话框 */}
      <FolderSelectDialog
        open={folderSelectDialogOpen}
        onOpenChange={setFolderSelectDialogOpen}
        onConfirm={handleConfirmImport}
      />

      {/* 确认对话框 */}
      <ConfirmDialog />
    </div>
  );
}